import React, { useState, useEffect } from "react";
import "./UserRoleSetting.css";

export default function UserRoleSetting() {
  const [users, setUsers] = useState([]);
  const [selectedUsername, setSelectedUsername] = useState("");
  const [selectedRole, setSelectedRole] = useState("");
  const [loading, setLoading] = useState(true);
  const [error, setError] = useState(null);
  const [successMessage, setSuccessMessage] = useState("");

  // 角色选项
  const roles = [
    { value: "ROLE_SUPER_ADMIN", label: "超级管理员ROLE_SUPER_ADMIN" },
    { value: "ROLE_STORE_MANAGER", label: "店长ROLE_STORE_MANAGER" }, // 移除多余空格

    { value: "ROLE_TICKET_SELLER", label: "售票员ROLE_TICKET_SELLER" },
  ];

  // 获取用户列表
  useEffect(() => {
    fetch("http://localhost:8080/api/users/all")
      .then((response) => {
        if (!response.ok) {
          throw new Error("获取用户列表失败");
        }
        return response.json();
      })
      .then((data) => {
        setUsers(data);
        setLoading(false);
      })
      .catch((error) => {
        setError(error.message);
        setLoading(false);
      });
  }, []);

  // 处理表单提交
  const handleSubmit = (e) => {
    e.preventDefault();

    if (!selectedUsername || !selectedRole) {
      setError("请选择用户和角色");
      return;
    }

    const requestBody = {
      username: selectedUsername,
      roleName: selectedRole,
    };

    fetch("http://localhost:8080/api/users/role/set", {
      method: "POST",
      headers: {
        "Content-Type": "application/json",
      },
      body: JSON.stringify(requestBody),
    })
      .then((response) => {
        if (!response.ok) {
          throw new Error("设置角色失败");
        }
        // 检查响应类型
        const contentType = response.headers.get("content-type");
        if (contentType && contentType.includes("application/json")) {
          return response.json();
        } else {
          return response.text(); // 处理纯文本响应
        }
      })
      .then((data) => {
        // 根据返回数据类型处理
        if (typeof data === "string") {
          // 如果是字符串，直接显示
          setSuccessMessage(data);
        } else {
          // 如果是JSON对象，按照原来的方式处理
          setSuccessMessage(
            `成功设置用户 ${selectedUsername} 的角色为 ${selectedRole}`
          );
        }
        setError(null);
        // 重置表单
        setSelectedUsername("");
        setSelectedRole("");
      })
      .catch((error) => {
        setError(error.message);
        setSuccessMessage("");
      });
  };

  if (loading) {
    return <div className="loading">加载中...</div>;
  }

  if (error) {
    return <div className="error">错误: {error}</div>;
  }

  return (
    <div className="user-role-setting-container">
      <h1>设置用户角色</h1>
      {successMessage && (
        <div className="success-message">{successMessage}</div>
      )}
      <form onSubmit={handleSubmit} className="role-setting-form">
        <div className="form-group">
          <label htmlFor="username">选择用户:</label>
          <select
            id="username"
            value={selectedUsername}
            onChange={(e) => setSelectedUsername(e.target.value)}
            required
          >
            <option value="">-- 请选择用户 --</option>
            {users.map((user) => (
              <option key={user.id} value={user.username}>
                {user.username} ({user.email})
              </option>
            ))}
          </select>
        </div>
        <div className="form-group">
          <label htmlFor="role">选择角色:</label>
          <select
            id="role"
            value={selectedRole}
            onChange={(e) => setSelectedRole(e.target.value)}
            required
          >
            <option value="">-- 请选择角色 --</option>
            {roles.map((role) => (
              <option key={role.value} value={role.value}>
                {role.label}
              </option>
            ))}
          </select>
        </div>
        <button type="submit" className="submit-button">
          设置角色
        </button>
      </form>
    </div>
  );
}
